import {Component} from 'react';

import {Boxs, SearchBar, Button,Popup} from 'saltui';

const {HBox, Box,} = Boxs;

import './tree.less';


const Item = React.createClass({

  checked: function (id) {
    this.props.checked(id);
  },
  showSubList: function (id) {
    this.props.showSubList(id);
  },


  render: function () {
    let t = this;
    return (
      <div>
        {
          this.props.todoList.map((item, key) => {
            return (
              <div>
                <HBox vAlign="center" className="dd-bottom-border ">
                  <Box className="t-PL16" onClick={this.checked.bind(t, item.id)}>
                    <div
                      className={item.checked ? 't-checkbox-field-icon-list' : 't-checkbox-field-icon-list un-checked'}>
                      <i className="iconfont icon-checked t-FCf t-FS14"></i>
                    </div>
                  </Box>
                  <Box className="t-PT12 t-PB12 t-PL10 t-PR6">
                    <i className="iconfont icon-personnelregister t-FCd t-FS20"></i>
                  </Box>
                  <HBox flex={1} onClick={this.showSubList.bind(t, item.id)}>
                    <Box flex={1} className="t-FS16 t-PL4 t-PR10 t-omit t-WB">{item.name}</Box>
                    <Box
                      className={(item.todo == null || item.todo == undefined || item.todo.length == 0) ? "t-DN" : "t-PR16"}>
                      <i
                        className={item.showSubList ? "iconfont icon-arrow-up t-rotate-180 t-FCc" : "iconfont icon-arrow-up t-rotate-90 t-FCc"}></i>
                    </Box>
                  </HBox>
                </HBox>
                <div className={item.showSubList ? "" : "t-DN"}>
                  {item.showSubList ?
                    <Item todoList={item.todo} showSubList={(id) => {
                      this.showSubList(id)
                    }} checked={(id) => {
                      this.checked(id)
                    }}/>
                    : ""}
                </div>
              </div>
            )
          })
        }

      </div>
    )
  }
});

export default class Page extends Component {
  constructor(props) {
    super(props);

    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    var height='';
    if(isAndroid==true){
        height = window.screen.height-70-44-58+"px";
    }else if(isiOS==true){
        height = window.screen.availHeight-70-44-27+"px";
    }else {
        if(window.screen.availHeight) {
            height = '550px';
        }
    }
    this.state = {
      //全选按钮
      checkedAll: false,

      //单选状态   radio checkbox
      checkbox: "checkbox",

      //已选择数据   只保存最高级
      selectData: [],
      //数据
      data: [],
      //处理后的数据
      todoList: [],

      //搜索 值
      search:"",
      //搜索出来的数组
      searchArr:[],

      visible:false,

      placeholder :"",

      height:height,
    };
  }

  componentWillMount() {
    //this.initData();
  }

  /*// 子组件初始化
  initState() {

  }*/

  //初始化数据
  initState() {
    let t = this;
    //数据
    let datas = t.props.data;
    let selectData = t.props.value;

    // 搜索提示语
    let placeholder = t.props.placeholder;
    if(placeholder == '' || placeholder == null){
      placeholder = "搜索";
    }

  
    if(selectData == null){
      selectData = [];
    }else{
      if(t.props.checked == 'radio'){
        selectData = [];
        selectData.push(t.props.value);
      }
    }
    if(datas == null){
      datas = [];
    }

    let dataArray = [];

    datas.forEach(function (data) {
      let checked = false;
      selectData.forEach(function (select) {
        if (select.id == data.id) {
          checked = true;
        }
      })
      let pid = data.pId;
      let id = data.id;
      let name = data.name;
      let objTemp = {
        "checked": checked,
        "showSubList": false,
        "show": true,
        "pid": pid,
        "id": id,
        "name": name
      }
      dataArray.push(objTemp);

    })
    t.setState({
        data: dataArray,
        selectData:selectData,
        visible:true,
        checkbox:t.props.checked,
        placeholder:placeholder,
      }, () => {
      if(t.state.checkbox != 'radio'){
        selectData.forEach(function (select) {
          t.bindCheckAll(select.id, true);
        })
        t.bindCheck();
      }
      t.getTreeFa()
    })
  }

  //获取父级节点  传入子节点查询
  getTreeFa() {
    let t = this;
    let dataArray = [];
    t.state.data.forEach(function (data) {
      var pid = data.pid;
      if (pid == '' || pid == null) {
        dataArray.push(data);
      }
    })
    let data = t.data2treeDG(t.state.data, dataArray);
    let checkedAll = true;
    for (let i = 0; i < t.state.data.length; i++) {
      if (!t.state.data[i].checked) {
        checkedAll = false;
      }
    }

    t.setState({
      todoList: data,
      checkedAll: checkedAll
    }, () => {
      let ttt = t.deepTraversal(t.state.todoList);
      let select = [];
      for (let i = 0; i < ttt.length; i++) {
        select.push({"id": ttt[i].id, "pid": ttt[i].pid,"name":ttt[i].name,"value":ttt[i].id,"text":ttt[i].name});
      }
      t.setState({selectData: select})
    })
  }

  //子节点拼接
  data2treeDG(datas, dataArray) {
    let t = this;
    //已经选中的
    let selectData = t.state.selectData;
    for (let j = 0; j < dataArray.length; j++) {
      let dataArrayIndex = dataArray[j];
      let childrenArray = [];
      let id1 = dataArrayIndex.id;

      for (let i = 0; i < datas.length; i++) {
        let data = datas[i];
        let pid = data.pid;
        if (pid == id1) {//判断是否为儿子节点
          childrenArray.push(data);
        }
      }
      dataArrayIndex.todo = childrenArray;
      if (childrenArray.length > 0) {//有儿子节点则递归
        t.data2treeDG(datas, childrenArray);
      }

    }
    return dataArray;
  }

  //深度优先遍历 ，非递归方法
  deepTraversal(node) {
    let nodes = [];
    for (let i = 0; i < node.length; i++) {
      let stack = [];//同来存放将来要访问的节点
      stack.push(node[i]);
      while (stack.length != 0) {
        let item = stack.pop();//正在访问的节点
        if (item.checked) {
          nodes.push(item);
        }
        let childrens = item.todo;
        //将现在访问点的节点的子节点存入stack，供将来访问
        if (!item.checked) {
          for (let i = childrens.length - 1; i >= 0; i--) {
            stack.push(childrens[i]);
          }
        }
      }
    }
    return nodes;
  }


  componentDidMount() {

  }

  //检查父节点节点需要选中
  bindCheck() {
    let t = this;
    let data = t.state.data;
    for (let i = 0; i < data.length; i++) {
      let ch = false;
      let end = true;
      for (let j = 0; j < data.length; j++) {
        if (data[i].id == data[j].pid) {
          end = false;
          ch = data[j].checked;
          if (!data[j].checked) {
            break;
          }
        }
      }
      if (end) {
        continue;
      }
      if (data[i].checked != ch) {
        data[i].checked = ch;
        i = -1;
      }

    }
  }

  //遍历子节点   选中或取消选中
  bindCheckAll(id, checked) {
    let t = this;
    let data = t.state.data;
    for (let i = 0; i < data.length; i++) {
      if (id == data[i].pid) {
        data[i].checked = checked;
        t.bindCheckAll(data[i].id, checked);
      }
    }
  }



  //选中
  checked(id) {
    let t = this;
    let json = t.state.data;
    if (t.state.checkbox == 'radio') {
      for (let i = 0; i < json.length; i++) {
        json[i].checked = false;
      }
    }
    // debugger;
    for (let i = 0; i < json.length; i++) {
      if (id == json[i].id) {
        if (t.state.checkbox == 'radio') {
          json[i].checked = true;
        } else {
          json[i].checked = !json[i].checked;
        t.bindCheckAll(id, json[i].checked);
        }
      }
    }
    // debugger;
    if (t.state.checkbox != 'radio') {
      t.bindCheck();
    }
    t.setState({
      data: json
    }, () => {
      if(t.state.search != ''){
         t.onSearch(t.state.search);
      }
      t.getTreeFa()
    })
  }


  //叶子展开
  showSubList(id) {
    let t = this;
    let json = t.state.data;
    for (let i = 0; i < json.length; i++) {
      if (id == json[i].id) {
        json[i].showSubList = !json[i].showSubList;
        break;
      }
    }
    t.setState({
      data: json
    }, () => {
      t.getTreeFa()
    })
  }


  //确定
  makesure() {
    let t = this;
    t.setState({
      visible: false
    }, () => {
      let  returnData = t.state.selectData;
      if(t.state.checkbox == 'radio'){
        if(returnData.length > 0){
          returnData = returnData[0];
        }else{
          returnData = {};
        }
      }
      this.props.onChange(returnData);
    });
  }

  //取消
  cancel() {
      // $("#App").removeAttr("style");
      // $(document).scrollTop(this.props.top);

      // this.setState({
      //   visible: false
      // });
      history.back();
  }

  //全选按钮
  selectAll() {
    let t = this;
    let isCheck = t.state.checkedAll;
    let data = t.state.data;
    t.setState({checkedAll: !t.state.checkedAll});
    for (let i = 0; i < data.length; i++) {
      data[i].checked = !isCheck;
    }
    t.getTreeFa();
  }

  //搜索
  onSearch(value){
    let t = this;
    let data = t.state.data;
    let searchArr = [];
    for(let i = 0 ; i < data.length ; i ++){
      if(data[i].name.indexOf(value)!=-1){
        console.log(data[i].name);
        console.log(value);
        searchArr.push({"id":data[i].id,"name":data[i].name,"checked":data[i].checked});
      }
    }
    t.setState({searchArr:searchArr})
  }


   // 点击蒙层关闭
   closMask(){
      this.props.closMask(this);
   }

  render() {
    const t = this;
    const props = {
      locale: 'zh_CN',
      placeholder:t.state.placeholder,
      instantSearch: false,
      hasHistory: true,
      searchDelay: 450,
      onEnter: () => {
      },
      onExit: () => {
        t.setState({search:"",searchArr:[]})
      },
      onChange: (value) => {
      },
      onSearch: (value) => {
        t.setState({search:value})
        t.onSearch(value);
      },
    };

    return (
      <div >
        <Popup
          content={ 


      <div className="t-BCf" style={{width:300}}>
        <SearchBar {...props} />
        <div className="dd-popup-container" style={{overflow:"auto" ,width:"100%",height:t.state.height}}>
        <div
          className={this.state.checkbox == 'radio' || (t.state.searchArr.length != 0 || t.state.search != "")?"t-DN":"t-PL16 t-PR16 t-PT10 t-PB10 dd-top-border dd-bottom-border" }>
          <HBox vAlign="center">
            <HBox onClick={t.selectAll.bind(t)}>
              <div
                className={this.state.checkedAll ? 't-checkbox-field-icon-list' : "t-checkbox-field-icon-list un-checked"}>
                <i className="iconfont icon-checked t-FCf t-FS14"></i>
              </div>
            </HBox>
            <Box flex={1} className="t-ML10">
              全选
            </Box>
          </HBox>
        </div>
        <div 
        className={this.state.checkbox == 'radio' || (t.state.searchArr.length != 0 || t.state.search != "")?"t-DN":"dd-bottom-border" }
        style={{height:5,width:"100%",backgroundColor:"#eee"}}></div>
        {
          t.state.searchArr.length == 0 && t.state.search == ''?
          <div  style={{marginBottom: 70}}>
            <Item todoList={t.state.todoList} showSubList={(id) => {
              t.showSubList(id)
            }} checked={(id) => {
              this.checked(id)
            }}/> </div>: 
            <div  style={{marginBottom: 70}}>
              {
                t.state.searchArr.map((item,key)=>(
                  <div>
                    <HBox vAlign="center" className="dd-bottom-border ">
                      <Box className="t-PL16" onClick={this.checked.bind(this,item.id)}>
                        <div className={item.checked?'t-checkbox-field-icon-list':'t-checkbox-field-icon-list un-checked'} >
                          <i className="iconfont icon-checked t-FCf t-FS14"></i>
                        </div>
                      </Box>
                      <Box className="t-PT12 t-PB12 t-PL10 t-PR6"><i className="iconfont icon-personnelregister t-FCd t-FS20"></i></Box>
                      <HBox flex={1} >
                        <Box flex={1} className="t-FS16 t-PL4 t-PR10 t-omit t-WB">{item.name}</Box>
                      </HBox>
                    </HBox>
                  </div>
                  ))
              }
            </div>
        }
        </div>

        <HBox vAlign="center" className="t-bottom-fixed t-P16 t-PT10 t-PB10">
          <Box flex={1}>

          </Box>
          <Box className="t-MR4">
            <Button type="secondary" size="small" display="inline" onClick={t.cancel.bind(t)}>取消</Button>
          </Box>
          <Box>
            <Button type="primary" size="small" display="inline" onClick={t.makesure.bind(t)}>确定</Button>
          </Box>
        </HBox>

      </div>

      }
          animationType="slide-left"
          onMaskClick={() => { this.setState({ visible: false });this.closMask(); }}
          visible={this.state.visible}
        >
          {null}
        </Popup>
     </div> 
    );
  }
}



